﻿using System;
using System.Threading;
using System.Web.UI;

using RaceList.activity.help;

namespace RaceList.activity.relay
{
    public partial class UserInfo : Page
    {
        private readonly object _obj = new object();

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            string name = txtName.Text.Trim();
            string phone = txtPhone.Text.Trim();
            string code = txtCode.Text.Trim();

            #region 数据验证

            if (string.IsNullOrEmpty(code))
            {
                this.Alert("兑奖码不能为空");
                txtCode.Focus();
                return;
            }
            if (string.IsNullOrEmpty(name))
            {
                this.Alert("姓名不能为空");
                txtName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(phone))
            {
                this.Alert("电话不能为空");
                txtPhone.Focus();
                return;
            }
            if (!RegexHelper.IsCNMobileNum(phone))
            {
                this.Alert("电话号码格式错误");
                txtPhone.Focus();
                return;
            }

            Activity_AwardUser awardUser = RelayQuery.GetActivity_AwardUser(code);
            if (awardUser == null)
            {
                this.Alert("兑奖码无效");
            }

            #endregion

            lock (_obj)
            {
                Thread.Sleep(new Random().Next(500, 1001));
                if (awardUser.isAward)
                {
                    this.Alert("兑奖码已使用，请耐心等待工作人员联系");
                    return;
                }

                RelayQuery.UpdateUserInfo(name, phone, code); //不论有没有奖品可以兑换用户都可以

                int? sponsorId = awardUser.Activity_Relay.SponsorId;
                var award = new Activity_Awards();
                string message = "";

                if (sponsorId.HasValue) //如果有的话就是景区门票
                {
                    award = RelayQuery.GetAward(sponsorId);
                    if (award != null)
                    {
                        RelayQuery.UpdateAwardInfo(award, code);

                        message = "你最近鸿运当头，获得了" + award.name;
                        this.Alert(message);
                        return;
                    }
                }

                award = RelayQuery.GetAward(null);

                if (award == null)
                {
                    this.Alert("前100位名额已满，下次早点来哦！");
                }
                RelayQuery.UpdateAwardInfo(award, code);

                message = "人品爆发，你获得了" + award.name;
                this.Alert(message);
            }
        }
    }
}